﻿using Lyq_VoteSys.Models;
using Lyq_VoteSys.Models.Database;
using Lyq_VoteSys.Serives;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Lyq_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class user : ControllerBase
    {
        private readonly lyqContext _db;
        private readonly JWTService _jwtService;
        public user(lyqContext db, JWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }


        [HttpPost]
        //用户注册（用户使用邮箱，密码进行注册，密码需要二次确认）
        public string Register(RegisterRequest request)
        {
            //密码二次确认
           if(request.Password!=request.CigPassword)
                return "两次密码输入不一致";
            var md5 = MD5Helper.MD5Encrypt32(request.Password);
            if (_db.Users.Any(x => x.Email == request.Email))
                return "邮箱地址已存在";
            _db.Users.Add(new User
            {
                
                Email = request.Email,
                Password = request.Password,
               
                

            });
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";

        }
        //用户登录（用户使用邮箱，密码进行登录，登录后可访问需要授权的页面）
        [HttpPost]
        public string Login(LoginRequest request)
        {
            var user = _db.Users.FirstOrDefault(x => x.Email == request.Email);
            if (user == null)
                return "用户不存在";
            if (user.Password != request.Password)
                return "密码不正确";
           return _jwtService.CreateToken((int)user.UserId,user.Email);
        }
    }
}
